package com.nubia.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nubia.utils.JwtUtils;
import com.nubia.utils.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class PublicInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        /**
         * 以下是跨域配置 不晓得对不对测试才晓得
         */
        System.out.println("Origin:"+request.getHeader("Origin"));
        response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));//HTTP 请求头获取源IP或域名　并配置到跨域源中　
        response.addHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,HEAD");
        response.addHeader("Access-Control-Max-Age", "3600000");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Headers", "Authentication,Origin, X-Requested-With, Content-Type, Accept,token");

            if(JwtUtils.analysisToken(token)){
                return true;
            }else {
                Map<String,Object> result = Result.resultDataString("非法操作",false,"token无效");
                String json = new ObjectMapper().writeValueAsString(result);
                response.setContentType("application/json; charset=UTF-8");
                //返回
                response.getWriter().println(json);
                return false;
            }


    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);


    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
